
let http          = require('http');
let formidable    = require('formidable');
let fs            = require('fs');
let path          = require('path');
let mkdirp        = require('mkdirp');
let targz         = require('tar.gz');
let config        = require('./config.js')
let util          = require('./util.js')
let exec          = require('child_process').exec;
let _0777         = parseInt('0755', 8) & (~process.umask());


class server{

    constructor(){
        this.port    = config.port;
        this.mustDir = config.mustDir;
        this.req     =null;
        this.res     =null;

        this.createServer();
    }

    //创建server
    createServer(){
        http.createServer((req, res)=> {
            this.req = req;
            this.res = res;
            console.log('---------')
            console.log(req.url)
            if(req.url == '/'){
                this.success('http-push 已经准备好了！')
            }else if(req.url.indexOf('/receiver') != -1 ){
                if(req.method.toLowerCase() != 'post') {
                    util.returnBeiZhu('请使用post请求!')
                    return false;
                }
                let form = new formidable.IncomingForm();
                form.parse(req, (err, fields, files) => {
                    if (err) { this.error(err); return; } 
               
                    let to       = fields['to']
                    let basesrc  = fields['basesrc']
                    let exclude  = fields['exclude']
                    let isDelDir = fields['isDelDir']

                    console.log(fields)

                    //清除记录 
                    this.deleteDir(basesrc,exclude,isDelDir)
                    .then(()=>{
                        this.writeBufferFile(to,files,basesrc) // 写入服务器
                    })

                });
            }
        })
        .listen(config.prot, () => {
            util.returnBeiZhu(`服务启动成功，监听的端口为${config.prot}`)
        });
    };

    // 删除服务端文件
    deleteDir(mkdir,exclude,isDelDir){
        return new Promise(function (resolve, reject) {
            console.log('进入了删除方法')
            let arr = ['/','/data','/bin','/usr','/root','/sys','/var','/sbin','/etc']
            let begin = true
            arr.forEach(item=>{
                if(mkdir == item) {
                    begin=false
                    resolve()
                    return false;
                }
            })
            if(!begin || mkdir.length<=6){
                resolve()
                return false;
            } 

            let shell=null

            if(isDelDir=='no') {
                resolve();
                return false;
            }

            console.log('进行删除')

            if(exclude){
                shell='find "'+mkdir+'" | grep -v "'+exclude+'" | xargs rm -rf'  
            }else{
                shell='rm -rf '+mkdir 
            }
            
            console.log('---------')
            console.log(shell)

            exec(shell,(err,out) => { 
                if(err) util.returnBeiZhu(`删除文件失败!\n ${err}`);

                resolve()
                util.returnBeiZhu('删除文件成功!')
            });
        })
        
    };

    // 向服务器里写入文件
    writeBufferFile(to,files,basesrc){
        console.log('进入了解压方法')
        fs.exists(to,(exists)=>{
            if (exists) {
                fs.unlink(to,  (err)=> this.next(files.file.path , to ,basesrc) );
            } else {
                fs.exists(path.dirname(to), (exists) => {
                    if (exists) {
                        this.next(files.file.path, to,basesrc);
                    } else {
                        mkdirp(path.dirname(to), _0777 ,(err)=> {

                            if (err) { this.error(err); return;}

                            this.next(files.file.path, to,basesrc);
                        });
                    }
                });
            }
        });
    };


    // 打印err 信息
    error(err) {
        this.res.writeHead(500, {'Content-Type': 'text/plain'});
        this.res.end(err.toString()); //fail
    }

    // request header
    success(str){
        this.res.writeHead(200, {'Content-Type': 'text/plain'});
        this.res.end(str);  
    }

    next(from , to ,basesrc) {
        console.log('进入了写入方法')
        fs.readFile(from, (err, content) => {

            if (err) { this.error(err); return; } 

            fs.writeFile(to, content, (err)=> {
                console.log('进入了写文件方法')
                if (err) { this.error(err); return; } 

                this.success('0');

                let arr=to.split('/')
                let arr1=[]
                arr.forEach((item,index)=>{
                    if(index>=arr.length-2) return;
                    arr1.push(item)
                })
                console.log('----解压数组---')
                console.log(arr1)
                console.log(arr1.join('/'))

                targz().extract(to, arr1.join('/'))
                    .then(()=>{
                        setTimeout(()=>{
                            exec(`chmod -R 755 ${basesrc}`,(err,out) => {
                                console.log('进入了重写文件权限方法')
                                if(err) util.returnBeiZhu(`设置文件权限失败！\n ${err}`);
                                util.returnBeiZhu('设置文件权限成功!');
                            });
                        },500)
                        util.returnBeiZhu('解压成功!');
                    })
                    .catch((err)=>{
                        util.returnBeiZhu(`解压失败! ${err.stack}`);
                    });
            });
        });
    }

}

// 启动服务
new server();









